// g++ ./bigsortc.cpp -std=c++11 -lpthread; ./a.out
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <chrono>
#include <pthread.h>

const int SIZE = 100000000;
const int THREAD_COUNT = 4;
std::vector<int> numbers(SIZE);

struct ThreadArgs {
    int left;
    int right;
};

// 归并两个已排序的向量
void merge(std::vector<int>& arr, int left, int mid, int right) {
    std::vector<int> temp(right - left + 1);
    int i = left, j = mid + 1, k = 0;

    while (i <= mid && j <= right) {
        if (arr[i] <= arr[j]) {
            temp[k++] = arr[i++];
        } else {
            temp[k++] = arr[j++];
        }
    }

    while (i <= mid) {
        temp[k++] = arr[i++];
    }

    while (j <= right) {
        temp[k++] = arr[j++];
    }

    for (int p = 0; p < k; p++) {
        arr[left + p] = temp[p];
    }
}

// 对向量的一部分进行排序
void* sortPart(void* arg) {
    ThreadArgs* args = static_cast<ThreadArgs*>(arg);
    std::sort(numbers.begin() + args->left, numbers.begin() + args->right + 1);
    delete args;
    return nullptr;
}

int main() {
    // 使用当前时间作为随机数生成器的种子
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 2000000000);  // 生成1到1000000之间的随机整数

    // 开始计时
    auto start = std::chrono::high_resolution_clock::now();

    // 生成随机数
    for (int i = 0; i < SIZE; ++i) {
        numbers[i] = dis(gen);
    }

    // 多线程排序
    pthread_t threads[THREAD_COUNT];
    int partSize = SIZE / THREAD_COUNT;
    for (int i = 0; i < THREAD_COUNT; ++i) {
        ThreadArgs* args = new ThreadArgs;
        args->left = i * partSize;
        args->right = (i == THREAD_COUNT - 1) ? SIZE - 1 : (i + 1) * partSize - 1;
        pthread_create(&threads[i], nullptr, sortPart, args);
    }

    // 等待所有线程完成
    for (int i = 0; i < THREAD_COUNT; ++i) {
        pthread_join(threads[i], nullptr);
    }

    // 归并排序结果
    for (int size = partSize; size < SIZE; size *= 2) {
        for (int i = 0; i < SIZE; i += 2 * size) {
            int left = i;
            int mid = std::min(i + size - 1, SIZE - 1);
            int right = std::min(i + 2 * size - 1, SIZE - 1);
            merge(numbers, left, mid, right);
        }
    }

    // 结束计时
    auto end = std::chrono::high_resolution_clock::now();

    // 计算耗时
    std::chrono::duration<double> diff = end - start;

    std::cout << "生成和排序 " << SIZE << " 个随机整数所需时间: " 
              << diff.count() << " 秒" << std::endl;

    return 0;
}
